import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:get/get.dart';

import 'package:flutter_deer/database/beans/get_all_goods_list.dart';
import 'package:flutter_deer/database/beans/pending_order_bean.dart';
import 'package:flutter_deer/database/database_manager.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/dl/dl.dart';
import 'package:flutter_deer/generated/res_upload_oil_entity.dart';

/// 挂单弹窗
class TakeOrdersDialog extends StatefulWidget {
  const TakeOrdersDialog({super.key});

  @override
  State<TakeOrdersDialog> createState() => _TakeOrdersDialogState();
}

class _TakeOrdersDialogState extends State<TakeOrdersDialog> {
  final List<PendingOrderBean> _orderList = [];
  CashierPageProvider mProvider = Get.find<CashierPageProvider>();

  @override
  void initState() {
    super.initState();
    _requestOrderList();
  }

  /// 请求可合并的油单列表
  void _requestOrderList() {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<PendingOrderBean>();
    final query = box.query().build().find();
    setState(() {
      _orderList.addAll(query);
    });
  }

  /// 选择订单
  void _onSelectOrder(PendingOrderBean bean) {
    final store = getIt<ObjectIdBox>().store;
    final box = store.box<PendingOrderBean>();

    // goodsList
    final dynamic decodedData = json.decode(bean.goodsList);
    if (decodedData is List<dynamic>) {
      final List<Map<String, dynamic>> goodsJsonList = decodedData.cast<Map<String, dynamic>>();
      final List<GetAllGoodsList> goodsList = goodsJsonList.map((json) => GetAllGoodsList.fromJson(json)).toList();
      mProvider.selectListGoods.assignAll(goodsList);
    } else {
      print('解码结果不是 List<dynamic> 类型');
    }

    // oilList
    final dynamic decodedDataOil = json.decode(bean.oilList);
    if (decodedDataOil is List<dynamic>) {
      final List<Map<String, dynamic>> oilJsonList = decodedDataOil.cast<Map<String, dynamic>>();
      final List<AppOrderBean> oilList = oilJsonList.map((json) => AppOrderBean.fromJson(json)).toList();
      mProvider.selectListOils.assignAll(oilList);
    } else {
      print('解码结果不是 List<dynamic> 类型');
    }

    // 去掉挂单时间
    final mList = <ResUploadOilEntity> [];
    for (final value in mProvider.selectListOils) {
      final mEntity = ResUploadOilEntity();
      mEntity.energyOrderCode = value.energyOrderCode;
      mEntity.suspendTime = '';
      mList.add(mEntity);
    }
    AppOrderBean.updatePendingTime(mList);

    box.remove(bean.id);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
      // insetPadding: EdgeInsets.all(20),
      child: SizedBox(
        width: 550,
        height: screenSize.height * 0.8,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Gaps.vGap15,
            _buildHeader(),
            Gaps.vGap15,
            Expanded(child: _buildOrderList()),
          ],
        ),
      ),
    );
  }

  /// 构建标题栏
  Widget _buildHeader() {
    String str = '枪号相同';
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Row(
            // 垂直方向基于基线对齐
            crossAxisAlignment: CrossAxisAlignment.baseline,
            // 指定使用字母基线
            textBaseline: TextBaseline.alphabetic,
            children: <Widget>[
              const SizedBox(width: 20),
              Text('挂单列表', style: TextStyles.textBold24.copyWith(color: Colours.dark_bg_color)),
              const SizedBox(width: 10),
              // Text('共${_orderList.length}笔${str}的油单，可选择进行合并收款', style: TextStyles.textSize16.copyWith(color: Colours.orange)),
              // RichText(
              //   text: TextSpan(
              //     children: [
              //       TextSpan(
              //         text: '共${_orderList.length}笔',
              //         style: TextStyles.textSize16.copyWith(color: Colours.orange),
              //       ),
              //       TextSpan(
              //         text: str,
              //         style: TextStyles.textSize16.copyWith(color: Colours.green),
              //       ),
              //       TextSpan(
              //         text: '的油单，请选择进行合并收款',
              //         style: TextStyles.textSize16.copyWith(color: Colours.orange),
              //       ),
              //     ],
              //   ),
              // ),
            ]),
        IconButton(
          icon: const Icon(Icons.close),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }

  /// 构建订单列表
  Widget _buildOrderList() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: ListView.builder(
        itemCount: _orderList.length,
        itemBuilder: (context, index) {
          if (index == _orderList.length) {
            return const Padding(
              padding: EdgeInsets.all(8.0),
              child: Center(child: CircularProgressIndicator()),
            );
          }
          final order = _orderList[index];
          return _buildOrderItem(order, index);
        },
      ),
    );
  }

  /// 构建订单项
  Widget _buildOrderItem(PendingOrderBean order, int index) {
    final isEven = index % 2 == 0;
    return InkWell(
      onTap: () {
        // 触发选择订单的方法
        _onSelectOrder(order);
      },
      child: Container(
        // width: 300,
        height: 65,
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        decoration: BoxDecoration(
          color: isEven ? const Color(0xFFDBDDE2) : Colors.white,
          borderRadius: BorderRadius.circular(3),
        ),
        child: Stack(
          children: [
            // 油品
            Positioned(left: 0, top: 0, child: Align(alignment: Alignment.topLeft, child: Text(order.descOil, textAlign: TextAlign.left))),
            // 总金额
            Positioned(right: 0, top: 0, child: Align(alignment: Alignment.topRight, child: Text('￥${order.descMny}', textAlign: TextAlign.right))),
            // 便利店
            Positioned(left: 0, bottom: 0, child: Align(alignment: Alignment.bottomLeft, child: Text(order.descShop, textAlign: TextAlign.left))),
            // 时间
            Positioned(right: 0, bottom: 0, child: Align(alignment: Alignment.bottomRight, child: Text(order.createTime, textAlign: TextAlign.right))),
          ],
        ),
      ),
    );
  }
}
